package httpresult

import (
	"fmt"
	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/rest/httpx"
	"go-exp/pkg/errorx"
	"go-exp/pkg/response"
	"google.golang.org/grpc/status"
	"net/http"
)

// http返回
func HttpResult(r *http.Request, w http.ResponseWriter, resp interface{}, err error) {
	if err == nil {
		//成功返回
		r := response.Response{
			Code: 200,
			Data: resp,
			Msg:  "操作成功",
		}
		httpx.WriteJson(w, http.StatusOK, r)
	} else {
		//错误返回
		caseErr := errors.Cause(err)
		codeError := errorx.NewCodeError(400, "")
		if e, ok := caseErr.(*errorx.CodeError); ok {
			codeError.Code = e.Code
			if e.Data != nil {
				codeError.Data = e.Data
			}
			codeError.Msg = e.Msg
		} else {
			if gstatus, ok := status.FromError(caseErr); ok { // grpc err错误
				grpcCode := uint32(gstatus.Code())
				codeError.Code = int(grpcCode)
				if gstatus.Details() != nil {
					codeError.Data = gstatus.Details()
				}
				codeError.Msg = gstatus.Message()
			}
		}
		logx.Errorf("%+v", codeError)

		logx.WithContext(r.Context()).Errorf("【API-ERR】 : %+v ", err)

		httpx.WriteJson(w, http.StatusBadRequest, codeError)
	}
}

func ParamErrorResult(w http.ResponseWriter, err error) {
	errMsg := fmt.Sprintf("%s ,%s", errorx.MapErrorCodeString(errorx.PARAM_ERROR), err.Error())
	httpx.WriteJson(w, http.StatusBadRequest, errorx.NewCodeError(400, errMsg))
}
